package com.situ.vivamarket.api.sys;


import com.situ.vivamarket.util.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping(value = "/sys/api/v1/upload",produces = MediaType.APPLICATION_JSON_VALUE)
public class UploadApi {
    @Value("${custom.file.upload.location}") //spring表达式，取得属性值
    private String uploadLocation;
    @PostMapping("/image")
    public ResponseEntity<JsonResult> uploadImage(MultipartFile file, String type) throws IOException { //默认值就是file
//       uploadLocation + File.separator + type ,即F:/IdeaProjects/Week10/upload/+/+member_avatar
        if(!StringUtils.hasText(type)){
            type="unknown";
        }
        File fileDir = new File(uploadLocation + File.separator + type);//用于创建目录
        if(!fileDir.exists()){
            boolean success=fileDir.mkdirs();
            if(!success){
                return ResponseEntity.internalServerError().body(JsonResult.fail("创建目录失败"));
            }
        }
//        生成文件名
        String fileName = file.getOriginalFilename();//上传时候的文件名
        String ext = fileName.substring(fileName.lastIndexOf("."));//扩展名，后缀
        fileName = UUID.randomUUID().toString() + ext;//全局，唯一的随机数
//      目标文件
        File desc = new File(fileDir.getCanonicalPath() + File.separator + fileName);
//    复制文件
        file.transferTo(desc);
//    响应数据
        return ResponseEntity.ok().body(JsonResult.successData(type+"/"+fileName));
    }
}
